import avatarAttachmentUploadTpl from './avatarAttachmentUpload.html';

function avatarAttachmentUploadComponent() {
  'ngInject';

  function linkFn(scope, elements, attrs, ctrl) {
    // setTimeout(ctrl.initUploader, 700);
  }

  let directive = {
    restrict: 'E',
    replace: true,
    templateUrl: avatarAttachmentUploadTpl,
    controller: avatarAttachmentUploadController,
    controllerAs: 'avatarAttachmentUploadCtrl',
    scope: true,
    bindToController: {
      fileList: '=',  // 用于绑定上传成返回的token和展示列表
      componentId: '@', // 传递组件id
      pickBtnId: '@', // 传递上传图片按钮id
      uploadUrl: '@', // 上传url
    },
    link: linkFn,
  };

  function avatarAttachmentUploadController($scope, fileUploaderService, $timeout) {
    'ngInject';
    let _this = this;
    const FILE_NUM_LIMIT = 2;

    // webuploader
    this.webuploader = {};

    // 删除文件
    this.delete = (item) => {
    	let index = this.fileList.indexOf(item);
    	if (index >= 0) {
    	  this.fileList.splice(index, 1);
    	}
    	let fileId = item.webuploaderFileId;
    	if (fileId) {
    		this.webuploader.removeFile(fileId);
    	}
    }

    function beforeFileQueuedCB() {
    	if (_this.fileList.length >= FILE_NUM_LIMIT) {
    		layer.alert(`最多可上传${FILE_NUM_LIMIT}个文件`);
    		return false;
    	}
  	}

    function fileQueuedCB() {};

    // 文件上传成功回调函数
    function uploadSuccessCB(file, resp) {   
      // this指向fileUploader
      let webuploader = this;

      let respToken = resp.message;
      console.log(_this.fileList);
     
    	$scope.$apply(() => {
	 			_this.fileList.push({
	 				id: respToken,
	 				fileName: file.name,
	 				webuploaderFileId: file.id,  // webuploader file 的id
	 			});
    	});

      // toast提示
      layer.msg(`${file.name}上传成功`);
    }

    // 文件上传失败回调函数
    function uploadErrorCB(file, reason) {
      layer.alert('文件上传失败');
    }

    // 上传设备基本信息
    this.initUploader = () => {
      // 初始化uploader
      let webuploader = fileUploaderService.initUploader({
        auto: true,
        pick: {
          id: `#${_this.pickBtnId}`,
          multiple: false,
        },
        duplicate: false,
        accept: null,
        server: this.uploadUrl,
      }, fileQueuedCB, uploadSuccessCB, uploadErrorCB);

      this.webuploader = webuploader;

      // 监听错误类型
      webuploader.on('error', function(type) {
        if (type == 'Q_EXCEED_NUM_LIMIT') {
          layer.alert(`最多可上传${FILE_NUM_LIMIT}个文件`);
        } else if (type == 'Q_TYPE_DENIED') {
          layer.alert('文件类型错误');
        }
      });
      // 监听是否超出文件最大上传数量
      webuploader.on('beforeFileQueued', beforeFileQueuedCB);
      
    }

    setTimeout(this.initUploader, 700);
  }

  return directive;
}

export default avatarAttachmentUploadComponent;
